package cn.falcon.fmobi.console.controller;

import cn.falcon.fmobi.biz.exception.CampaignValidateException;
import cn.falcon.fmobi.biz.exception.StrategyValidateException;
import cn.falcon.fmobi.biz.exception.TargetValidateException;
import cn.falcon.fmobi.biz.service.CreativeService;
import cn.falcon.fmobi.biz.service.StrategyService;
import cn.falcon.fmobi.biz.vo.StrategyDetailVo;
import cn.falcon.fmobi.console.common.RestfulJsonModelAndView;
import cn.falcon.fmobi.console.common.Result;
import cn.falcon.fmobi.console.constant.UrlConstant;
import cn.falcon.fmobi.console.constant.UserRolePermission;
import cn.falcon.fmobi.console.exception.CallBackException;
import cn.falcon.fmobi.console.exception.ParamValidateException;
import cn.falcon.fmobi.console.requestparam.Query;
import cn.falcon.fmobi.console.requestparam.StrategyParam;
import cn.falcon.fmobi.dao.enumration.FeeType;
import cn.falcon.fmobi.dao.enumration.StrategyStatus;
import cn.falcon.fmobi.dao.po.Strategy;
import cn.falcon.fmobi.dao.util.DataUtils;
import cn.falcon.fmobi.dao.util.ValidateUtil;
import cn.falcon.marketing.api.response.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.text.ParseException;
import java.util.Map;

/**
 * User: shirongkang
 * Date: 2017/9/22
 * Time: 11:13
 * Desc:策略
 */
@Controller
@RequestMapping(UrlConstant.STRATEGY_URL)
public class StrategyCtrl extends BaseCtrl{


    @Autowired
    private StrategyService strategyService;

    @Autowired
    private CreativeService creativeService;

//    @Autowired
//    private TargetPackageService targetPackageService;

    /**
     * 策略列表
     * @return
     */
    @RequestMapping(method = RequestMethod.GET)
    public ModelAndView getListPage(@PathVariable("campaignId") Integer campaignId, Query query)
        throws ParamValidateException {
        if(null == query.getStartDate() || null == query.getEndDate()) {
            throw new ParamValidateException(Result.ERR_MISS_PARAMETER,"startDate、endDate", "Result.err.miss.parameter");
        }
        if(query.getStartDate().getTime() > query.getEndDate().getTime()) {
            throw new ParamValidateException(Result.ERR_INVALID_PARAMETER,"startDate、endDate", "Result.err.invalid.parameter");
        }
        Map<String,Object> param = query.getSearch();
        param.put("campaignId",campaignId);
        param.put("advertiserId",this.getActorId(UserRolePermission.USER_ROLE_ADVERTISER));
        param.put("agentId",this.getActorId(UserRolePermission.USER_ROLE_AGENT));
        param.put("promotionPlanId",query.getPromotionPlanId());
        return RestfulJsonModelAndView.buildJsonModelAndView(strategyService.listPage(param,query.getPageInfo()));
    }
    /**
     * 策略详情
     * @return
     */
    @RequestMapping(method = RequestMethod.GET,value = "{strategyId}")
    public ModelAndView getDetail(@PathVariable("strategyId") Integer strategyId){
        return RestfulJsonModelAndView.buildJsonModelAndView(strategyService.get(strategyId));
    }

    /**
     * 策略下广告位列表
     * @return
     */
    @RequestMapping(method = RequestMethod.GET,value = "space")
    public ModelAndView getSpaceListPage(@PathVariable("campaignId") Integer campaignId, Query query){
        Map<String,Object> param = query.getSearch();
        param.put("campaignId",campaignId);
        param.put("mediaId",query.getMediaId());
        param.put("promotionPlanId",query.getPromotionPlanId());
        return RestfulJsonModelAndView.buildJsonModelAndView(strategyService.strategySpaceListVoListPage(param,query.getPageInfo()));
    }

    /**
     *  策略下创意列表
     * @return
     */
    @RequestMapping(method = RequestMethod.GET,value = "creative")
    public ModelAndView getCreativeListPage(Query query)
        throws ParamValidateException {
        if(null == query.getPromotionPlanId() || 0 >= query.getPromotionPlanId()) {
            throw new ParamValidateException(Result.ERR_MISS_PARAMETER,"promotionPlanId", "Result.err.miss.parameter");
        }
        if(null == query.getSpaceId() || 0 >= query.getSpaceId()) {
            throw new ParamValidateException(Result.ERR_MISS_PARAMETER,"spaceId", "Result.err.miss.parameter");
        }
        Map<String,Object> param = query.getSearch();
        param.put("promotionPlanId",query.getPromotionPlanId());
        param.put("spaceId",query.getSpaceId());
        return RestfulJsonModelAndView.buildJsonModelAndView(creativeService.findCreativeList(param,query.getPageInfo(),false));
    }

    /**
     * 编辑策略
     * @return
     */
    @RequestMapping(method = {RequestMethod.POST,RequestMethod.PUT})
    public ModelAndView addOrEdit(@PathVariable("campaignId") Integer campaignId,@RequestBody StrategyParam strategyParam)
        throws ParamValidateException, UnsupportedEncodingException, ParseException {
        this.check(strategyParam);
        Strategy strategy = strategyParam.getStrategy();
//        Integer targetPacageId = null;
//        if(null == strategyParam.getTargetPackageId() || 0 >= strategyParam.getTargetPackageId()) {
//            targetPacageId = targetPackageService.add(strategyParam.getTargetInfo());
//            if(0 == targetPacageId) {
//                throw new ParamValidateException(Result.ERR_INVALID_PARAMETER,"新增定向包失败，请联系管理员", "Result.err.invalid.parameter");
//            }
//        }
//        strategy.setTargetPackageId(targetPacageId);
        strategy.setCampaignId(campaignId);
        try {
            if(0 < strategyParam.getId()) {
                strategyService.update(strategy,strategyParam.getTargetInfo());
            }else {
                strategyService.add(strategy,strategyParam.getTargetInfo());
            }
        }catch (StrategyValidateException e) {
            throw new CallBackException(e.getCode().getValue(),e.getCode().getDesc());
        }catch (CampaignValidateException e1) {
            throw new CallBackException(e1.getCode().getValue(),e1.getCode().getDesc());
        }catch (TargetValidateException e2) {
            throw new CallBackException(e2.getCode().getValue(),e2.getCode().getDesc());
        }
        return RestfulJsonModelAndView.buildJsonModelAndView();
    }

    /**
     * 快捷编辑状态
     * @param campaignId
     * @param strategyParam
     * @return
     * @throws ParamValidateException
     */
    @RequestMapping(method = RequestMethod.PUT,value = "status")
    public ModelAndView updateStatus(@PathVariable("campaignId") Integer campaignId,@RequestBody StrategyParam strategyParam) throws ParamValidateException {
        if(0 >= strategyParam.getId()) {
            throw new ParamValidateException(Result.ERR_INVALID_PARAMETER,"id", "Result.err.invalid.parameter");
        }
        if(null == strategyParam.getStatus() || 0 > strategyParam.getStatus()) {
            throw new ParamValidateException(Result.ERR_INVALID_PARAMETER,"status", "Result.err.invalid.parameter");
        }
        try {
            StrategyDetailVo strategyDetailVo = strategyService.get(strategyParam.getId());
            //验证需要发生数据改变策略的状态是否是有效或者暂停
            if(StrategyStatus.ADSTATUS_VAILD.getValue() == strategyDetailVo.getStatus() ||
                StrategyStatus.ADSTATUS_SUSPEND.getValue() == strategyDetailVo.getStatus()) {
                strategyParam.setCampaignId(campaignId);
                strategyParam.setPromotionPlanId(strategyDetailVo.getPromotionPlanId());
                strategyService.updateStatus(strategyParam,strategyDetailVo);
            }else {
                throw new ParamValidateException(Result.ERR_INVALID_PARAMETER,"status", "Result.err.invalid.parameter");
            }
        }catch (StrategyValidateException e) {
            throw new CallBackException(e.getCode().getValue(),e.getCode().getDesc());
        }
        return RestfulJsonModelAndView.buildJsonModelAndView();
    }

    /**
     * 快捷编辑出价
     * @param campaignId
     * @param strategyParam
     * @return
     * @throws ParamValidateException
     */
    @RequestMapping(method = RequestMethod.PUT,value = "price")
    public ModelAndView updatePrice(@PathVariable("campaignId") Integer campaignId,@RequestBody StrategyParam strategyParam) throws ParamValidateException {
        if(0 >= strategyParam.getId()) {
            throw new ParamValidateException(Result.ERR_INVALID_PARAMETER,"id", "Result.err.invalid.parameter");
        }
        if(null == strategyParam.getUnitPrice()) {
            throw new ParamValidateException(Result.ERR_MISS_PARAMETER,"unitPrice", "Result.err.miss.parameter");
        }
        try {
            StrategyDetailVo strategyDetailVo = strategyService.get(strategyParam.getId());
            //验证需要发生数据改变策略的状态是否是已被删除
            if(StrategyStatus.ADSTATUS_DELETED.getValue() != strategyDetailVo.getStatus()) {
                strategyParam.setCampaignId(campaignId);
                strategyParam.setPromotionPlanId(strategyDetailVo.getPromotionPlanId());
                strategyParam.setFeeType(strategyDetailVo.getFeeType());
                strategyService.updatePrice(strategyParam);
            }else {
                throw new ParamValidateException(Result.ERR_INVALID_PARAMETER,"status", "Result.err.invalid.parameter");
            }
        }catch (StrategyValidateException e) {
            throw new CallBackException(e.getCode().getValue(),e.getCode().getDesc());
        }
        return RestfulJsonModelAndView.buildJsonModelAndView();
    }

    /**
     * 验证几次数据的准确性
     * @param strategyParam
     * @throws ParamValidateException
     * @throws UnsupportedEncodingException
     */
    private void check(StrategyParam strategyParam) throws ParamValidateException, UnsupportedEncodingException {
        if(null == strategyParam) {
            throw new ParamValidateException(Result.ERR_MISS_PARAMETER,"参数都为空", "Result.err.miss.parameter");
        }
        if(DataUtils.isNull(strategyParam.getName())) {
            throw new ParamValidateException(Result.ERR_MISS_PARAMETER,"name", "Result.err.miss.parameter");
        }
        if(ValidateUtil.checkLength(strategyParam.getName(),100)) {
            throw new ParamValidateException(Result.ERR_MISS_PARAMETER,"name", "Result.err.invalid.length");
        }
        if(DataUtils.isNull(strategyParam.getPromotionPlanId())) {
            throw new ParamValidateException(Result.ERR_MISS_PARAMETER,"promptionPlanId", "Result.err.miss.parameter");
        }
        if(DataUtils.isNull(strategyParam.getType())) {
            throw new ParamValidateException(Result.ERR_MISS_PARAMETER,"type", "Result.err.miss.parameter");
        }
        if(null == strategyParam.getStartTime()) {
            throw new ParamValidateException(Result.ERR_MISS_PARAMETER,"startDate", "Result.err.miss.parameter");
        }
        if(null == strategyParam.getEndTime()) {
            throw new ParamValidateException(Result.ERR_MISS_PARAMETER,"endDate", "Result.err.miss.parameter");
        }
        if(DataUtils.isNull(strategyParam.getSpaceId())) {
            throw new ParamValidateException(Result.ERR_MISS_PARAMETER,"spaceId", "Result.err.miss.parameter");
        }
        if(DataUtils.isNull(strategyParam.getCreativeId())) {
            throw new ParamValidateException(Result.ERR_MISS_PARAMETER,"creativeId", "Result.err.miss.parameter");
        }
        //是否是新建定向信息
        if(DataUtils.isNull(strategyParam.getTargetPackageId())) {
            if(null == strategyParam.getTargetParam()) {
                throw new ParamValidateException(Result.ERR_MISS_PARAMETER,"targetParam", "Result.err.miss.parameter");
            }
            if(DataUtils.isNull(strategyParam.getTargetParam().getType())) {
                throw new ParamValidateException(Result.ERR_MISS_PARAMETER,"type", "Result.err.miss.parameter");
            }
            if(null == strategyParam.getTargetParam().getHours() &&
                DataUtils.isNull(strategyParam.getTargetParam().getArea()) &&
                null == strategyParam.getTargetParam().getAge() &&
                null == strategyParam.getTargetParam().getMarriage() &&
                null == strategyParam.getTargetParam().getEducation() &&
                null == strategyParam.getTargetParam().getGender() &&
                null == strategyParam.getTargetParam().getInterests() &&
                null == strategyParam.getTargetParam().getConnection() &&
                null == strategyParam.getTargetParam().getOs() &&
                null == strategyParam.getTargetParam().getTelcom() &&
                null == strategyParam.getTargetParam().getBehavior() &&
                DataUtils.isNull(strategyParam.getTargetParam().getKeyword()) &&
                (null !=  strategyParam.getTargetParam().getBehavior() &&
                null == strategyParam.getTargetParam().getBehavior().getActIds() &&
                null == strategyParam.getTargetParam().getBehavior().getObjectIds() &&
                null == strategyParam.getTargetParam().getBehavior().getTimeWindow() &&

                null == strategyParam.getTargetParam().getCustomAudience())) {
                throw new ParamValidateException(Result.ERR_MISS_PARAMETER,"targetParam", "Result.err.miss.parameter");
            }
            if(DataUtils.isNull(strategyParam.getTargetName())) {
                throw new ParamValidateException(Result.ERR_MISS_PARAMETER,"targteName", "Result.err.miss.parameter");
            }
            //验证时间定向数据的准确性
            if(null != strategyParam.getTargetParam().getHours()) {
                if(strategyParam.getTargetParam().getHours().length != 7) {
                    throw new ParamValidateException(Result.ERR_INVALID_PARAMETER,"targetParam.hours", "Result.err.invalid.parameter");
                }
                for (Integer[] integers : strategyParam.getTargetParam().getHours()) {
                    if(integers.length != 24) {
                        throw new ParamValidateException(Result.ERR_INVALID_PARAMETER,"targetParam.hours", "Result.err.invalid.parameter");
                    }
                    for (Integer integer : integers) {
                        if(integer != 0 && integer != 1) {
                            throw new ParamValidateException(Result.ERR_INVALID_PARAMETER,"targetParam.hours", "Result.err.invalid.parameter");
                        }
                    }
                }
            }
        }
        if(null == strategyParam.getUnitPrice()) {
            throw new ParamValidateException(Result.ERR_MISS_PARAMETER,"unitPrice", "Result.err.miss.parameter");
        }
//        if(DataUtils.isNull(strategyParam.getFeeType())) {
//            throw new ParamValidateException(Result.ERR_MISS_PARAMETER,"feeType", "Result.err.miss.parameter");
//        }else if(!FeeType.mapping.containsKey(strategyParam.getFeeType())) {
//            throw new ParamValidateException(Result.ERR_MISS_PARAMETER,"feeType", "Result.err.invalid.parameter");
//        }

    }








}
